package com.abe.libcore.utils.net;

import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.RequiresApi;

import com.abe.libcore.ConstantCore;
import com.abe.libcore.utils.CommonUtils;
import com.abe.libcore.utils.context.ContextUtils;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class NetworkCallbackImpl extends ConnectivityManager.NetworkCallback {
    @Override
    public void onAvailable(Network network) {
        super.onAvailable(network);
        CommonUtils.INSTANCE.log("NetworkCallbackImpl-onAvailable: 网络已连接");
        post(true);
    }

    @Override
    public void onLost(Network network) {
        super.onLost(network);
        CommonUtils.INSTANCE.log("NetworkCallbackImpl-onLost: 网络已断开");
        post(false);
    }

    @Override
    public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
        super.onCapabilitiesChanged(network, networkCapabilities);
        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                CommonUtils.INSTANCE.log("NetworkCallbackImpl-onCapabilitiesChanged: 网络类型为wifi");
                post(true, NetworkCapabilities.TRANSPORT_WIFI);
            } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                CommonUtils.INSTANCE.log("NetworkCallbackImpl-onCapabilitiesChanged: 蜂窝网络");
                post(true, NetworkCapabilities.TRANSPORT_CELLULAR);
            } else {
                CommonUtils.INSTANCE.log("NetworkCallbackImpl-onCapabilitiesChanged: 其他网络");
                post(true);
            }
        }
    }

    private void post(boolean isConnect, int... transportType) {
        Bundle bundle = new Bundle();
        bundle.putBoolean("state", isConnect);
        if (transportType.length > 0)
            bundle.putInt("type", transportType[0]);
        Intent appIntent = new Intent(ConstantCore.NetWorkState);
        appIntent.putExtras(bundle);
        ContextUtils.Companion.getContext().sendBroadcast(appIntent);
    }
}